/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  dyeOrder
 *  DyeOrder
 */



/***** variables declartion section, begin *****/
var dyeOrderInputMode = wacFormInputMode.add;
var dyeOrderObj = {};
var dyeOrderAuditAction = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        dyeOrderAuditAction = new DyeOrderAuditAction();

        initDyeOrderFormDialog();

        initDyeOrderForm();

        bindDyeOrderEvents();
    }
);

function bindDyeOrderEvents()
{
    $("#dyeOrderFormDialog").bind('dialogopen', function(event, ui)
    {
        initDyeOrderFormData();
//        $(".ui-widget-overlay").appendTo($("#appStorehouse"));
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.dyeOrder.name);//
    });

    $("#dyeOrderFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#dyeOrder_btnSubmit").bind('click', function (e)
    {
        submitDyeOrderForm();
    });

    $("#dyeOrder_btnClose").bind('click', function (e)
    {
        $("#dyeOrderFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t12003")
        {
            $("div[aria-labelledby='ui-dialog-title-dyeOrderFormDialog']").remove();
            $("#dyeOrderFormDialog").remove();
        }
    });
}


function initDyeOrderFormDialog()
{
//    wacDebugLog("initDyeOrderFormDialog.");
    $("#dyeOrderFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 850,
            height: 550,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });

     
//     $("#dyeOrderFormDialog").parent().appendTo($("#appStorehouse"));

}

function initDyeOrderForm()
{
    $("#dyeOrderForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#dyeOrder_start_date, #dyeOrder_delivery_date").datepicker();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initDyeOrderFormData()
{
    wacShowBlockUILoading("#dyeOrderFormDialog");
    $('#dyeOrder_supplier_id, #dyeOrder_production_order_id, #dyeOrder_goods_amount_unit_code').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "dyeOrder/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initDyeOrderFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initDyeOrderFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#dyeOrder_goods_amount_unit_code");
        }
   }

   setupDyeOrderFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#dyeOrderFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupDyeOrderFormDefaultValues(defaultValueObj)
{
    if(dyeOrderInputMode == wacFormInputMode.add)   // use default values
    {
        $("#dyeOrder_id").attr("value", 0);
        $('#dyeOrder_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#dyeOrder_supplier_id').flexbox(BASE_URL + 'factory/GetDyeFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "supplier_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });


        $("#dyeOrder_goods_amount_unit_code option:[value='"+ defaultValueObj.cotton_unit_code +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#dyeOrder_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: dyeOrderObj.production_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#dyeOrder_production_order_id_input').val(dyeOrderObj.production_order_code);

        $('#dyeOrder_supplier_id').flexbox(BASE_URL + 'factory/GetDyeFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: dyeOrderObj.supplier_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "supplier_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#dyeOrder_supplier_id_input').val(dyeOrderObj.supplier_name);

        $("#dyeOrder_start_date").attr("value", dyeOrderObj.start_date);
        $("#dyeOrder_delivery_date").attr("value", dyeOrderObj.delivery_date);
        $("#dyeOrder_code").attr("value", dyeOrderObj.code);
        $("#dyeOrder_id").attr("value", dyeOrderObj.id);
        $("#dyeOrder_memo").attr("value", dyeOrderObj.memo);

        $("#dyeOrder_goods_amount_unit_code option:[value='"+ dyeOrderObj.goods_amount_unit_code +"']").attr('selected', 'selected');
        $("#dyeOrder_supplier_id option:[value='"+ dyeOrderObj.supplier_id +"']").attr('selected', 'selected');
    }

//    wacDebugLog($.dump(dyeOrderObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("dyeOrderInputMode: " + dyeOrderInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/
// audit class
function DyeOrderAuditAction(){
    this.run = function(orderId){
        dyeOrderAudit(orderId);
    }
}

function dyeOrderAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "dye_order_id" : orderId
    };
//    dyeOrderObj = $("#dyeOrderList").getRowData(orderId);
//    console.log($.dump(dyeOrderObj));

    $.ajax({
        url: BASE_URL + "dyeOrder/audit",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            dyeOrderAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function dyeOrderAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#dyeOrderList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function dyeOrderOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    dyeOrderInputMode = inputMode;

    if(rowid === undefined){
        dyeOrderObj = {};
    }
    else
    {
        dyeOrderObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateDyeOrderForm()
{
    var validateFlag = true;

    if (!$("#dyeOrderForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    var startDate    = $("#dyeOrder_start_date").datepicker( 'getDate' );
    var deliveryDate = $("#dyeOrder_delivery_date").datepicker( 'getDate' );
    if(deliveryDate <= startDate)
    {
        wacShowTips("发货日期不得早于开始日期!");
        validateFlag = false;
    }

    return validateFlag;
}

function submitDyeOrderForm()
{
    if(!validateDyeOrderForm()){
        return;
    }

    wacShowBlockUILoading("#dyeOrderFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(dyeOrderInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "dyeOrder/add";
    }
    else{
        submitUrl = BASE_URL + "dyeOrder/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#dyeOrderForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitDyeOrderFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitDyeOrderFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#dyeOrderList").trigger("reloadGrid");
   }

   wacHideBlockUI("#dyeOrderFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/